package com.rtf.framework.monitor.export;

import com.rtf.framework.monitor.AppMonitorExporter;
import com.rtf.framework.monitor.config.AppMonitorProperties;
import com.rtf.framework.monitor.support.AppRequestInfo;
import com.rtf.framework.monitor.support.AppRequestPool;
import com.google.common.collect.Lists;
import io.prometheus.client.Collector;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.GaugeMetricFamily;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 基于url请求导出并发量、平均响应时间、错数数量信息
 * @Author : liupeng
 * @Date : 2020-02-01
 * @Modified By
 */
public class AppUrlTraceExport extends Collector implements AppMonitorExporter {
    @Override
    public String getName() {
        return "request_trace";
    }

    @Override
    public synchronized void export(CollectorRegistry collectorRegistry ) {

        new AppUrlTraceExport().register( collectorRegistry ) ;
    }

    @Override
    public List<MetricFamilySamples> collect() {
        List<MetricFamilySamples> mfs = Lists.newArrayList( ) ;

        Map<String, AppRequestInfo> requestInfos =
                AppRequestPool.getLastRequestInfo( System.currentTimeMillis() ) ;

        if( requestInfos==null || requestInfos.size()<1 ){
            return mfs ;
        }

        // 标签属性
        List<String> labels = Arrays.asList("uri" , "appName") ;

        GaugeMetricFamily currentNum = new GaugeMetricFamily("uri_currentnum",
                "uri并发量", labels ) ;

        GaugeMetricFamily currentFailNum = new GaugeMetricFamily("uri_current_fail_num",
                "uri失败数量", labels ) ;

        GaugeMetricFamily currentAvgTime = new GaugeMetricFamily("uri_avgtime",
                "uri平均响应时间(ms)", labels ) ;

        for (Map.Entry<String, AppRequestInfo> entry : requestInfos.entrySet()) {
            List<String> labelValues = Lists.newArrayList( entry.getKey() , AppMonitorProperties.getAppName()  ) ;

            currentNum.addMetric( labelValues , entry.getValue().getNum().doubleValue() ) ;

            currentFailNum.addMetric( labelValues , entry.getValue().getFailNum().doubleValue() ) ;

            currentAvgTime.addMetric( labelValues , entry.getValue().getTotalDuration().longValue() / entry.getValue().getNum().doubleValue()  ) ;
        }

        mfs.addAll( Lists.newArrayList( currentNum , currentAvgTime , currentFailNum ) ) ;

        return mfs ;
    }
}
